package com.czh.web;

import com.czh.Unitl.SqlSessionFactoryUtils;
import com.czh.mapper.UserMapper;
import com.czh.pojo.User;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/registerServlet")
public class RegisterServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //第一句 就是设置编码
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        User user=new User();
        user.setUsername(username);
        user.setPassword(password);
        SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();
        SqlSession sqlSession = sqlSessionFactory.openSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user1 = mapper.selectByName(username);
        PrintWriter writer = resp.getWriter();
        if(user1!=null){
            writer.write("注册失败，用户名重复");
            sqlSession.close();
        }
        else {
            mapper.add(user);
            sqlSession.commit();
            sqlSession.close();
            writer.write("注册成功");
        }

    }

}